﻿using Consul;

namespace order.Config
{
    public static class ServiceDiscoveryExtensions
    {
        public static void RegisterConsulServices(this IServiceCollection services, ConsulRegisterOptions cnsulRegisterOptions)
        {
            if (cnsulRegisterOptions == null)
            {
                throw new ArgumentNullException(nameof(cnsulRegisterOptions));
            }

            var consulClient = CreateConsulClient(cnsulRegisterOptions);

            services.AddSingleton(cnsulRegisterOptions);
            services.AddSingleton<IHostedService, ServiceDiscoveryHostedService>();
            services.AddSingleton<IConsulClient, ConsulClient>(p => consulClient);
        }

        private static ConsulClient CreateConsulClient(ConsulRegisterOptions cnsulRegisterOptions)
        {
            return new ConsulClient(config =>
            {
                config.Address = cnsulRegisterOptions.ServiceDiscoveryAddress;
            });
        }
    }
}
